import { PixijsRender } from "../PixijsRender";
import { ViewState } from "./PixijsEntities";
import { PixijsWorld } from "./PixijsWorld";
import cloneDeep from "lodash.clonedeep";

export enum EntityFlags {
    Selected = 1 << 0,
    Resize = 1 << 1,
    Delete = 1 << 2,
    All = 0xffffffff    
}

export class BaseEntity {
    deviceId: string;
    id: number;
    position: { x: number; y: number; }
    anchor: { x: number, y: number }
    //单位是角度
    rotation: number;
    name: string;
    children: BaseEntity[]
    scale: { x: number, y: number }
    skew: { x: number, y: number };

    parent?: BaseEntity;
    selected?: boolean;
    drag?: boolean;
    resize?: number;
    hover?: boolean;
    locked?: boolean;
    visible?: boolean;
    expanded?: boolean;
    url?: string
    view?: any;
    viewState?: ViewState;
    isPrefab?: boolean;

    className: string;
    flags: number;
    //编辑用，缓存数据
    //世界坐标
    __worldPosition?: { x: number; y: number; }
    __rotation?: number;
    __size?: { w: number, h: number }

    protected __render: PixijsRender;

    constructor(pixiRender?: PixijsRender) {
        this.__render = pixiRender;
        this.id = PixijsWorld.GetID();
        this.position = { x: 0, y: 0 }
        this.scale = { x: 1, y: 1 }
        this.anchor = { x: 0.5, y: 0.5 }
        this.skew = { x: 0.0, y: 0.0 }
        this.rotation = 0;
        this.name = "";
        this.children = [];
        this.className = this.constructor.name
        this.flags = EntityFlags.All;
        this.viewState = ViewState.WaitLoad;
    }

    unloadAssets() {
  
    }

    addChild(child: BaseEntity, at?: number) {
        // 确保子节点没有父节点
        if (child.parent) {
            child.removeFromParent();
        }

        // 如果 at 未提供或超出当前子节点范围，则添加到最后
        if (at === undefined || at < 0 || at > this.children.length) {
            this.children.push(child); // 添加到最后
            if (child.view) this.view?.addChild(child.view);
        } else {
            this.children.splice(at, 0, child); // 添加到指定位置
            if (child.view) this.view?.addChildAt(child.view, at);
        }

        child.parent = this; // 设置父节点
    }

    removeFromParent() {
        if (this.parent) {
            const index = this.parent.children.indexOf(this);
            if (index !== -1) {
                this.parent.children.splice(index, 1); // 从父节点的子节点中移除
            }
            if (this.view) this.view.removeFromParent();
            this.parent = undefined; // 清除父节点引用
        }
    }

    toJson() {
        const jsonObject: { [key: string]: any } = {
            className: this.constructor.name, // 导出类名
        };
        Object.entries(this).forEach(([key, value]) => {
            if (!key.startsWith('__') && typeof value !== 'function' && key !== 'children' && key !== 'view' && key !== 'parent') {
                jsonObject[key] = cloneDeep(value);
            }
            else if (key === 'children' && !this.isPrefab) {
                jsonObject[key] = [];
                this.children.forEach(c => {
                    jsonObject[key].push(c.id);
                })
            }
        });
        return jsonObject;
    }

    fromJson(json: { [key: string]: any }) {
        // 遍历 JSON 对象的属性
        Object.entries(json).forEach(([key, value]) => {
            // 过滤掉以 '__' 开头的属性
            if (!key.startsWith('__') && key !== 'children' && key !== 'id') {
                //@ts-ignore
                this[key] = value; // 赋值
            }
        });

        this.viewState = ViewState.WaitLoad;
    }

    get size() {
        let width = Math.abs((this.scale.x * this.view.getLocalBounds().width));
        let height = Math.abs((this.scale.y * this.view.getLocalBounds().height));
        return {
            width, height
        }
    }

    set size(s: { width: number, height: number }) {
        this.view.width = s.width;
        this.view.height = s.height;
        this.scale.x = this.view.scale.x;
        this.scale.y = this.view.scale.y;
    }

    applyData(_data?: any) {
        this.view.angle = this.rotation;
        //console.log(entity.position.x, entity.position.y)
        this.view.position.set(this.position.x, this.position.y);
        this.view.visible = this.visible;
        //@ts-ignore
        this.view.anchor?.set(this.anchor.x, this.anchor.y);
        this.view.skew.x = this.skew.x;
        this.view.skew.y = this.skew.y;
        this.view.scale.x = this.scale.x;
        this.view.scale.y = this.scale.y;
    }

    hasFlag(flag: EntityFlags) {
        return (this.flags & flag) !== 0;
    }

    /**
     * 设置标志位
     * @param flag 
     * @param value 
     */
    setFlag(flag: EntityFlags, value: boolean) {
        if (value) {
            this.flags |= flag;
        } else {
            this.flags &= ~flag;    
        }
    }

    loadAssets() { }
}